<template>
  <div v-loading="loading" class="add-edit-wrap">
    <el-form
      :model="detailInfo"
      :rules="rules"
      ref="detailInfoFormRef"
      label-width="120px"
    >
      <el-form-item label="比赛开始时间" prop="startTime">
        <el-date-picker
          v-model="detailInfo.startTime"
          type="datetime"
          placeholder="选择比赛开始时间"
          default-time="12:00:00"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="比赛结束时间" prop="endTime">
        <el-date-picker
          v-model="detailInfo.endTime"
          type="datetime"
          placeholder="选择比赛结束时间"
          default-time="12:00:00"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="对战队伍名称" prop="otherTeamName">
        <el-input
          v-model="detailInfo.otherTeamName"
          :maxlength="20"
          class="custom-input"
          clearable
          placeholder="请输入对战队伍名称"
        ></el-input>
      </el-form-item>

      <el-form-item label="结果">
        <div style="display: flex">
          <el-form-item style="display: inline" prop="myTeamScore">
            <el-input
              v-model="detailInfo.myTeamScore"
              v-interage
              style="width: 150px"
              placeholder="请输入本方队伍得分"
            >
            </el-input>
          </el-form-item>

          <span style="margin: 0 10px"> : </span>
          <el-form-item style="display: inline" prop="otherTeamScore">
            <el-input
              v-model="detailInfo.otherTeamScore"
              v-interage
              style="width: 150px"
              placeholder="请输入对战队伍得分"
            >
            </el-input>
          </el-form-item>
        </div>
      </el-form-item>

      <el-form-item label="参赛队员">
        <div>
          <el-button type="primary" icon="el-icon-plus" @click="handleAddPlayer"
            >增加</el-button
          >
        </div>
        <el-table
          v-loading="tableLoading"
          :data="playerList"
          style="width: 90%"
          height="490px"
        >
          <el-table-column label="姓名" fixed="left" minWidth="200">
            <template slot-scope="scope">
              <el-select v-model="scope.row.id">
                <el-option
                  v-for="item in playerOptionList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="上场时间" minWidth="200">
            <template slot-scope="scope">
              <el-input-number
                v-model.number="scope.row.shangchangTime"
                :control="false"
                :min="0"
                :max="100"
                clearable
                placeholder="请输入球员上场时间"
              ></el-input-number
              ><span>min</span>
            </template>
          </el-table-column>
          <el-table-column label="得分" minWidth="180">
            <template slot-scope="scope">
              <el-input-number
                v-model.number="scope.row.score"
                :control="false"
                :min="0"
                :max="100"
                clearable
                placeholder="请输入球员得分"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="助攻" minWidth="180">
            <template slot-scope="scope">
              <el-input-number
                v-model.number="scope.row.assistNumber"
                :control="false"
                :min="0"
                :max="100"
                clearable
                placeholder="请输入球员助攻"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="犯规" minWidth="180">
            <template slot-scope="scope">
              <el-input-number
                v-model.number="scope.row.foulNumber"
                :control="false"
                :min="0"
                :max="100"
                clearable
                placeholder="请输入球员犯规"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="过人" minWidth="180">
            <template slot-scope="scope">
              <el-input-number
                v-model.number="scope.row.outstanding"
                :control="false"
                :min="0"
                :max="100"
                clearable
                placeholder="请输入球员过人"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="扑救" minWidth="180">
            <template slot-scope="scope">
              <el-input-number
                v-model.number="scope.row.diveNumber"
                :control="false"
                :min="0"
                :max="100"
                clearable
                placeholder="请输入球员解围"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="解围" minWidth="180">
            <template slot-scope="scope">
              <el-input-number
                v-model.number="scope.row.helpNumber"
                :control="false"
                :min="0"
                :max="100"
                clearable
                placeholder="请输入球员解围"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" minWidth="120">
            <template slot-scope="scope">
              <el-button
                type="text"
                :disabled="!canDelete(scope.row)"
                @click="handleDeletePlayer(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item v-if="type === 'add'">
        <el-button type="primary" @click="handleAddRace"
          >立即新增比赛</el-button
        >
        <el-button @click="handleReset('add')">重置</el-button>
      </el-form-item>
      <el-form-item v-if="type === 'edit'">
        <el-button type="primary" @click="handleEditRace">提交修改</el-button>
        <el-button @click="handleReset('edit')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  fetchRaceDetailData,
  fetchRaceAdd,
  fetchRaceEdit,
  fetchRacePlayerListData,
} from "@/api/race/index";
import { fetchPLayerOptions } from "@/api/player/index";
import moment from "moment";
import { PLAYER_POSITION } from "@/views/player/constants/index";
export default {
  name: "add-edit-race",
  data() {
    const validateScore = (rule, value, callback) => {
      console.log(rule);
      if (!value) {
        callback();
      }
      if (value < 0 || value > 100) {
        callback(new Error("分数范围为0-100"));
      } else {
        callback();
      }
    };
    return {
      PLAYER_POSITION,
      loading: false,
      tableLoading: false,
      detailInfo: {
        startTime: null,
        endTime: null,
        otherTeamName: "",
        myTeamScore: "",
        otherTeamScore: "",
        // id: "",
        // position: "",
        // clothNumber: "",
      },
      rules: {
        otherTeamName: [
          { required: true, message: "请输入对战队伍名称", trigger: "blur" },
        ],
        startTime: [
          { required: true, message: "请输入比赛开始时间", trigger: "blur" },
        ],
        endTime: [
          { required: true, message: "请输入比赛结束时间", trigger: "blur" },
        ],
        myTeamScore: [
          { required: true, message: "请输入本方得分", trigger: "blur" },
          { validator: validateScore, trigger: "blur" },
        ],
        otherTeamScore: [
          { required: true, message: "请输入对方得分", trigger: "blur" },
          { validator: validateScore, trigger: "blur" },
        ],
      },
      playerOption: [],
      playerList: [
        {
          id: "",
          score: 0,
          shangchangTime: 0,
          assistNumber: 0,
          foulNumber: 0,
          outstanding: 0,
          diveNumber: 0,
          helpNumber: 0,
        },
      ],
    };
  },
  computed: {
    type() {
      return this.$route?.query?.type || "add";
    },
    id() {
      return this.$route?.query?.id || null;
    },
    playerOptionList({ playerOption, playerList }) {
      const idList = playerList.map((el) => el.id);
      const returnList = playerOption.map((el) => {
        return {
          ...el,
          disabled: idList.includes(el.id),
        };
      });
      return returnList;
    },
  },
  created() {
    this.requestPLayerOptions();
    if (this.type === "edit") {
      this.requestRaceDetailData();
      this.requestRacePlayerListData();
    }
  },
  methods: {
    /**
     * 是否可以删除
     */
    canDelete(row) {
      let flag = false;
      if (this.type === "edit") {
        flag = false;
      } else {
        if (this.playerList.length <= 1) {
          flag = false;
        } else {
          if ((row?.id ?? "") !== "") {
            flag = true;
          } else {
            flag = false;
          }
        }
      }

      return flag;
    },
    /**
     * 重置
     */
    handleReset(type) {
      if (type === "add") {
        this.detailInfo = this.$options.data().detailInfo;
        this.playerList = this.$options.data().playerList;
      } else {
        this.requestRaceDetailData();
        this.requestRacePlayerListData();
      }
      this.$refs.detailInfoFormRef.clearValidate();
    },
    /**
     * 添加比赛
     */
    handleAddRace() {
      const playerList = this.playerList;
      if (!playerList.every((el) => (el.id ?? "") !== "")) {
        this.$message.warning("请先将所有队员信息填完");
        return false;
      }
      if (playerList.length >= 20) {
        this.$message.warning("最多添加20个队员");
        return false;
      }
      if (playerList.length < 1) {
        this.$message.warning("最少需要保留1个参赛队员");
        return false;
      }
      this.$refs.detailInfoFormRef.validate((valid) => {
        if (valid) {
          this.requestRaceAdd();
        } else {
          return false;
        }
      });
    },
    /**
     * 编辑比赛
     */
    handleEditRace() {
      const playerList = this.playerList;
      if (!playerList.every((el) => (el.id ?? "") !== "")) {
        this.$message.warning("请先将所有队员信息填完");
        return false;
      }
      if (playerList.length >= 20) {
        this.$message.warning("最多添加20个队员");
        return false;
      }
      if (playerList.length < 1) {
        this.$message.warning("最少需要保留1个参赛队员");
        return false;
      }
      this.$refs.detailInfoFormRef.validate((valid) => {
        if (valid) {
          this.requestRaceEdit();
        } else {
          return false;
        }
      });
    },
    /**
     * 删除队员
     */
    handleDeletePlayer(row) {
      const currentId = row?.id;
      const playerList = this.playerList;
      const idList = playerList.map((el) => el.id);
      const currentIndex = idList.indexOf(currentId);
      if (currentIndex < 0) {
        return false;
      }
      if (playerList.length <= 1) {
        this.$message.warning("最少需要保留1个参赛队员");
        return false;
      }
      this.playerList = playerList.filter((el) => el.id !== currentId);
    },
    /**
     * 添加队员
     */
    handleAddPlayer() {
      const playerList = this.playerList;
      if (!playerList.every((el) => (el.id ?? "") !== "")) {
        this.$message.warning("请先将所有队员信息填完");
        return false;
      }
      if (playerList.length >= 20) {
        this.$message.warning("最多添加20个队员");
        return false;
      }
      const item = {
        id: "",
        score: 0,
        shangchangTime: 0,
        assistNumber: 0,
        foulNumber: 0,
        outstanding: 0,
        diveNumber: 0,
        helpNumber: 0,
      };
      this.playerList = this.playerList.concat([item]);
    },
    /**
     * 请求全部队员 不带分页 用于下拉框
     */
    requestPLayerOptions() {
      fetchPLayerOptions().then((res) => {
        console.log(res, "请求全部队员");
        this.playerOption = res?.data || [];
      });
    },
    /**
     * 请求详情
     */
    requestRaceDetailData() {
      this.loading = true;
      const params = {
        id: this.id,
      };
      fetchRaceDetailData(params)
        .then((res) => {
          this.detailInfo = res?.data || {};
          this.detailInfo.position = res?.data?.position
            ? String(res?.data?.position)
            : "";
          this.$refs.detailInfoFormRef.clearValidate();
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.detailInfo = this.$options.data().detailInfo;
          this.$refs.detailInfoFormRef.clearValidate();
          this.loading = false;
        });
    },
    /**
     * 请求参赛队员
     */
    requestRacePlayerListData() {
      this.tableLoading = true;
      const params = {
        id: this.id,
      };
      fetchRacePlayerListData(params)
        .then((res) => {
          this.tableLoading = false;
          this.playerList = res?.data || this.$options.data().playerList;
        })
        .catch((err) => {
          console.log(err);
          this.tableLoading = false;
        });
    },
    /**
     * 请求新增
     */
    requestRaceAdd() {
      const params = { ...this.detailInfo, playerList: this.playerList };
      params.startTime = moment(this.detailInfo.startTime).valueOf();
      params.endTime = moment(this.detailInfo.endTime).valueOf();
      this.loading = true;
      fetchRaceAdd(params)
        .then((res) => {
          if (res?.code === 1 && res?.data) {
            this.$message.success("新增成功！");
            this.$router.push({ name: "race-list" });
          }
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    /**
     * 请求编辑
     */
    requestRaceEdit() {
      const params = { ...this.detailInfo, playerList: this.playerList };
      params.startTime = moment(this.detailInfo.startTime).valueOf();
      params.endTime = moment(this.detailInfo.endTime).valueOf();
      params.id = this.id;
      this.loading = true;
      fetchRaceEdit(params)
        .then((res) => {
          if (res?.code === 1 && res?.data) {
            this.$message.success("更新成功！");
            this.$router.push({ name: "race-list" });
          }
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
  },
};
</script>

<style scoped>
.custom-input {
  width: 240px;
}
</style>
